#include "image.h"
#include "connect.h"

#define NUM_PAR 5

/**
 * Create the camera module. It sends a stream of images of width xheight to the interpolator.
 * @param argv[1] the server address
 * @param argv[2] width of the image
 * @param argv[3] height of the image
 * @param argv[4] lenght og the stream
 */

int main (int argc, char *argv []) {

	int sock = 0, count = 0, i = 0, width = 0, height = 0, dim = 0, stream = 0;
	unsigned char *image = NULL;

	struct hostent *server;
	struct sockaddr_in serv_addr;

#ifdef DEBUG
#define PATH_OPERAZIONI "./Debug/Gaussian_"
#define DIM 30
    char path [DIM];
    char numim [DIM];
#endif
    
	if (argc != NUM_PAR)
		error("Error in the arguments");

	/* open the socket*/
	if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0)
		error("Error opening socket");

	/* take the IP address from the firts argument of the program */
	if ((server = gethostbyname (argv[1])) == NULL)
		error("Error in Ip address");

	/* set the dimension */
	width = atoi (argv[2]);
	height = atoi (argv[3]);
    stream = atoi (argv[4]);

	dim = width * height;	

	/* set the address and the port of the server */
	memset( (char *) &serv_addr, ZERO, sizeof (serv_addr));
	serv_addr.sin_family = AF_INET;
	memcpy( (char *) &serv_addr.sin_addr.s_addr, (char *) server->h_addr, server->h_length);
	serv_addr.sin_port = htons (PORT);
    
	/* connect the client to server */
	while (connect (sock, (struct sockaddr*) &serv_addr, sizeof (serv_addr)) < 0) {
		sleep(1);
		if (++count == MAX_TRY)	
			error("Unable to contact server");
	}
	
	/* send the parameters to server */
	if(Write(sock, &width, sizeof(int)) < sizeof (int))
		error("Error writing the width of the image");
	if(Write(sock, &height, sizeof(int)) < sizeof (int))
		error("Error writing the height of the image");
	if(Write(sock, &stream, sizeof(int)) < sizeof (int))
		error("Error writing the length of the stream");

	for(i = 0; i < stream; i++) {

		/* create the image */
		image = createImage(width ,height);
		
#ifdef DEBUG
        
        /* create the path */
        strcpy (path, PATH_OPERAZIONI);
		sprintf(numim, "%d", i);
		strcat (path, numim);
		strcat (path, ".tiff");
        
        /* write the image */
        writeImage (image, path, width, height);
        
#endif
        
        /* write and close the socket */
		if(Write(sock, image, dim) < dim){
			printf("error is %d\n", errno);
			error("Error writing the image");
		}
        
		/* free the memory */
		free(image);
	}
	
	if (close(sock) < 0)
		error("Error closing the socket");

	return 0;
}
